/**
 * Copyright © 2015 - 2017 EntDIY JavaEE Development Framework
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bolt.support.spring.mvc.method;


import com.bolt.common.convert.Convert;
import com.bolt.common.utils.DateUtil;
import com.bolt.common.utils.StrUtil;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.SignStyle;
import java.util.Date;

import static java.time.temporal.ChronoField.*;

@ControllerAdvice
public class GlobalBindingInitializer {

    public static final DateTimeFormatter LOCAL_DATE_FORMATTER;

    public static final DateTimeFormatter LOCAL_DATE_TIME_FORMATTER;


    static {
        LOCAL_DATE_FORMATTER = new DateTimeFormatterBuilder()
                .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
                .appendLiteral('-')
                .appendValue(MONTH_OF_YEAR, 2)
                .appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2)
                .toFormatter();

        LOCAL_DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(DateTimeFormatter.ISO_LOCAL_DATE)
                .appendLiteral(' ')
                .appendValue(HOUR_OF_DAY, 2)
                .appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2)
                .optionalStart()
                .appendLiteral(':')
                .appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();
    }


    @InitBinder
    public void registerCustomEditors(WebDataBinder binder) {

        //自定义类型属性转换，动态处理日期、时间等不同格式数据转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StrUtil.isBlank(text)) {
                    // Treat empty String as null value.
                    setValue(null);
                } else {
                    setValue(DateUtil.parseDate(text));
                }
            }

            @Override
            public String getAsText() {
                Date value = (Date) getValue();
                return (value != null ? DateUtil.formatDate(value) : "");
            }
        });
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StrUtil.isBlank(text)) {
                    // Treat empty String as null value.
                    setValue(null);
                } else {
                    setValue(LocalDate.parse(text, LOCAL_DATE_FORMATTER));
                }
            }

            @Override
            public String getAsText() {
                LocalDate value = (LocalDate) getValue();
                return (value != null ? value.format(LOCAL_DATE_FORMATTER) : "");
            }
        });
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StrUtil.isBlank(text)) {
                    // Treat empty String as null value.
                    setValue(null);
                } else {
                    setValue(LocalDateTime.parse(text, LOCAL_DATE_TIME_FORMATTER));
                }
            }

            @Override
            public String getAsText() {
                LocalDateTime value = (LocalDateTime) getValue();
                return (value != null ? value.format(LOCAL_DATE_TIME_FORMATTER) : "");
            }
        });

        binder.registerCustomEditor(Integer.TYPE, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(Integer.valueOf(Convert.toInt(text, 0)));
            }
        });
        binder.registerCustomEditor(Double.TYPE, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(Double.valueOf(Convert.toDouble(text, 0.0D)));
            }
        });
        binder.registerCustomEditor(Long.TYPE, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(Long.valueOf(Convert.toLong(text, 0L)));
            }
        });
        // Converts empty strings into null when a form is submitted
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));

    }
}
